package com.wqz.tacos.controller;

import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import  org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;

import com.wqz.tacos.models.Order;

@Slf4j
@Controller
@RequestMapping("/orders")
public class OrderController {
    @GetMapping("/current")
    public String OrderForm(Model model) {
        model.addAttribute("order", new Order());
        log.info("enter order view");
        return "orderForm";
    }

    // 对于/orders的请求的处理
    // 对于提交的表单需要进行是否是合法输入的校验
    // 添加校验的方式可以在processOrder方法中或者在model中的Order类中添加校验，后者可读性更高
    // 在model添加校验后，需要在post方法中添加@Valid注解，告诉Controller需要进行校验
    @PostMapping
    public String processOrder(@Valid Order order, Errors errors) {
        if (errors.hasErrors()) {
            log.info("errors occurred and it is " + errors.toString());
            return "orderForm";
        }
        log.info("Order submitted: " + order);
        // 重定向到home
        return "redirect:/";
    }
}
